﻿using Se.Model.Template;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using Se.Model.GameModel.Character;
using Se.Common;
using Se.Log;

namespace Se.Model.GameModel.Card
{
    /// <summary>
    /// 牌桌
    /// </summary>
    public class CardTable
    {
        public CardTable(long tableId, TableTemplate tableTemplate)
        {
            this.TableId = tableId;
            this.TableTemplate = tableTemplate;
            this.Players = new ConcurrentDictionary<int, CardPlayer>();
            this.State = TableState.Waiting;
        }

        /// <summary>
        /// 牌桌模板
        /// </summary>
        public readonly TableTemplate TableTemplate;

        /// <summary>
        /// 牌桌Id
        /// </summary>
        public long TableId { get; set; }
        /// <summary>
        /// 随机对象
        /// </summary>
        private Random rdmCard = new Random();

        /// <summary>
        /// 玩家操作锁
        /// </summary>
        public object _opearateLocker = new object();

        /// <summary>
        /// 玩家（座位号，Player）
        /// </summary>
        public ConcurrentDictionary<int, CardPlayer> Players { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public TableState State { get; set; }

        /// <summary>
        /// 进入房间
        /// </summary>
        /// <returns></returns>
        public ResultInfo TryEnter(Player player)
        {
            if (this.State != TableState.Waiting) return ResultInfo.SetResult(false, "房间不在等待中，无法进入");

            if (this.Players.Count >= this.TableTemplate.MaxPlayerCount) return ResultInfo.SetResult(false, "房间已满");

            var cardPlayer = new CardPlayer(this, player);
            cardPlayer.SeatIndex = GetEmptySeat();
            if (!this.Players.TryAdd(cardPlayer.SeatIndex, cardPlayer)) return ResultInfo.SetResult(false, "进入房间失败");

            return ResultInfo.SetResult();
        }


        /// <summary>
        /// 获取空座位
        /// </summary>
        /// <returns></returns>
        public int GetEmptySeat()
        {
            for (var i = 1; i <= this.TableTemplate.MaxPlayerCount; i++)
            {
                if (!this.Players.ContainsKey(i))
                    return i;
            }
            throw new Exception("没有找到空座位,tableid:" + this.TableId);
        }


        /// <summary>
        /// 开始牌桌游戏
        /// </summary>
        /// <returns></returns>
        public ResultInfo TryStartTableGame()
        {
            lock (this._opearateLocker)
            {
                //if (!this.CanStartGame())
                //{
                //    return ResultInfo.SetResult(false, "无法开始游戏");
                //}
                //this.Round.Status = TableStatus.Beginning;
                //this.ResetAllCardsSet();
                //int[] playerSeats;
                //foreach (var waitingPlayer in this.WaitingPlayers)
                //{
                //    // 非机器人 掉线的玩家，将不会添加到玩家列表中
                //    if (!waitingPlayer.Value.IsRobot)
                //    {
                //        if (waitingPlayer.Value.Session == null || waitingPlayer.Value.Session.Status != SocketSessionStatus.Connected)
                //        {
                //            SeLog.Info("PokerTable->TryStartPokerGame 玩家{0} 已经离线", waitingPlayer.Value.NickName);
                //            continue;
                //        }
                //    }
                //    waitingPlayer.Value.Cards.Clear();
                //    waitingPlayer.Value.CoinAdded = 0;
                //    this.PlayingPlayers.TryAdd(waitingPlayer.Key, waitingPlayer.Value);

                //}
                //this.WaitingPlayers.Clear();

                //this.GameId = this.GetNewID();
                //bool canSeat = this.GetEmptySeat() > 0;

                //PlayLog startLog = PlayLog.Start(this.PlayingPlayers.Values.ToList().ToStringBySeats(), canSeat, this.GameId);
                //this.SendPlayerLog(startLog);

                //playerSeats = this.PlayingPlayers.Keys.ToArray();

                //this.Round.StartNewRound(playerSeats);

                //this.Prize.ResetPrize(this.PlayingPlayers.Values.ToList().ConvertAll<long>(c => c.Id).ToArray(), this.BigBlindsCoin);


                //SeLog.Info("table {0} 开始游戏", TableId);
                //var realPlayerIds = this.PlayingPlayers.Where(c => !c.Value.IsRobot).Select(c => c.Value.Id);
                //if (realPlayerIds.Count() > 0)
                //    GameCache.proxy.BeginGame(realPlayerIds.ToArray());

                //// 大盲注小盲注下注
                //var smallCoinSeat = GetNextSeatIndex(this.PlayingPlayers.Keys.ToArray(), this.Round.DealerSeatIndex);//庄家的上家为小盲注
                //var bigCoinSeat = GetNextSeatIndex(this.PlayingPlayers.Keys.ToArray(), smallCoinSeat);//庄家的上家为小盲注
                //this.CardAddCoin(this.PlayingPlayers[smallCoinSeat].Id, this.SmallBlindsCoin, true);
                //this.Prize.CurrentCoin = BigBlindsCoin;
                //this.CardAddCoin(this.PlayingPlayers[bigCoinSeat].Id, this.BigBlindsCoin, true);
                //this.PlayingPlayers[smallCoinSeat].LastOperate = GameOperateEnum.SmallBlinds;
                //this.PlayingPlayers[bigCoinSeat].LastOperate = GameOperateEnum.BigBlinds;

                //// 广播日志
                //PlayLog _dealerLog = PlayLog.DealerSeat(this.Round.DealerSeatIndex);
                //var bigBlindsLog = PlayLog.BigBlinds(bigCoinSeat, this.BigBlindsCoin);
                //var smallBlindsLog = PlayLog.SmallBlinds(smallCoinSeat, this.SmallBlindsCoin);
                //this.SendPlayerLog(_dealerLog);
                //this.SendPlayerLog(smallBlindsLog);
                //this.SendPlayerLog(bigBlindsLog);
                //this.SendChangeCoinLog(this.PlayingPlayers[smallCoinSeat]);
                //this.SendChangeCoinLog(this.PlayingPlayers[bigCoinSeat]);
                //this.SendPrizeChangedPoolLog();
                ////发牌
                //foreach (var playerItem in this.PlayingPlayers)
                //{
                //    SeLog.Info("table {0} 发玩家牌", TableId);
                //    var cards = this.GetRandomCards(2);
                //    playerItem.Value.Cards.AddRange(cards);
                //    int cardIndex = 0;
                //    cards.ForEach(c =>
                //    {
                //        PlayLog sendLog = PlayLog.SendPoker(playerItem.Value.SeatNumber, ++cardIndex, c.ToString());
                //        this.SendPlayLog(playerItem.Value, sendLog);
                //    });
                //}
                //this.Round.Status = TableStatus.InProgress;

                //this.SetNextSeatPlayer(bigCoinSeat);
                //this.UpdateLastOperateTime();

                return ResultInfo.SetResult();
            }
        }



        /// <summary>
        /// 是否可以开始游戏
        /// </summary>
        /// <returns></returns>
        private bool CanStartGame()
        {
            //TODO

            return false;
        }

        /// <summary>
        /// 获取下一个玩家的座位号
        /// </summary>
        /// <param name="seats"></param>
        /// <param name="currentSeat"></param>
        /// <returns></returns>
        private int GetNextSeatIndex(int[] seats, int currentSeat)
        {
            if (seats.Length == 0)
            {
                return 0;
            }
            var newSeats = seats.OrderBy(c => c).ToArray();
            foreach (var seat in newSeats)
            {
                if (seat > currentSeat)
                {
                    return seat;
                }
            }
            return newSeats[0];
        }
    }
}
